package cn.opencodes.framework.core.interceptor;


import java.text.MessageFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.opencodes.framework.core.service.AlphaService;
import cn.opencodes.framework.core.utils.SpringUtils;
import cn.opencodes.framework.core.utils.WebUtils;
import cn.opencodes.framework.core.vo.AccessLog;
import cn.opencodes.framework.core.vo.UserRoot;
import cn.opencodes.framework.tools.utils.DateUtils;
import cn.opencodes.framework.tools.utils.JsonUtils;

/**
 * 日志访问拦截器
 */
public class AccessInterceptor extends HandlerInterceptorAdapter {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private final String ACCESS_TIME_KEY = "access_time_key";

	

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	 /**设置访问请求开始时间**/
    	long stime = System.currentTimeMillis();
    	request.setAttribute(ACCESS_TIME_KEY, stime);
        return true;
    }
	
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    	saveAccessLog(request, response);
    }
   
    
    /**保存访问日志**/
    private void saveAccessLog(HttpServletRequest request, HttpServletResponse response){
    	final Long stime = (Long)request.getAttribute(ACCESS_TIME_KEY);
		final Long etime = System.currentTimeMillis();
		String title = MessageFormat.format("{0} - {1}", 
				DateUtils.format(new Date(stime), "mm:ss.SSS"),
				DateUtils.format(new Date(etime), "mm:ss.SSS"));
		AccessLog log = new AccessLog();
		try {
			UserRoot user = WebUtils.getUser();
			log.setUserName(user.getUsername());
			log.setUserAgent(WebUtils.analyticUserAgent(request).toString());
			log.setCtime(new Date());
			log.setMethod(request.getMethod());
			log.setRequestUrl(request.getServletPath());
			log.setClientHost(WebUtils.getIpAddr(request));
			log.setParameters(JsonUtils.toJson(request.getParameterMap()));
			log.setStatus(response.getStatus());
			log.setConsumeTime(etime - stime);
			log.setTitle(title);
			//收集日志
			SpringUtils.getBean(AlphaService.class).collect(log, AccessLog.class);
		} catch (Exception e) {
			logger.error("访问日志拦截器异常:",e);
		}
    }
    
}
